import { createRouter, createWebHashHistory } from 'vue-router'
import Login from '../views/Login.vue'
import MainBox from '../views/MainBox.vue'
import RoutesConfig from './config'
import store from '@/store'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/mainBox',
    name: 'mainBox',
    component: MainBox,
    // 路由动态添加
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由跳转之前
router.beforeEach((to, from, next) => {
  if (to.name === 'login') {
    next()
  } else {
    // 授权登录成功后 next()
    // 未授权，重定向到login
    if (!localStorage.getItem('token')) {
      ElMessage.error('无权限，正在登出')
      next({
        path: '/login'
      })
    } else {
      if (!store.state.isGetterRouter) {
        // 判断是否为第一次
        // 删除所有嵌套路由 mainBox
        router.removeRoute('mainBox')
        ConfigRouter()
        next({
          path: to.fullPath
        })
      } else {
        next()
      }
    }
  }
})

function loadView(view)
{
    // 路由懒加载
    return () => import(view);
}
const ConfigRouter = () => {
  if (!router.hasRoute('mainBox')) {
    router.addRoute({
      path: '/mainBox',
      name: 'mainBox',
      component: MainBox
      // 路由动态添加
    })
  }
  const routerList = [...store.state.roleMenuList, ...RoutesConfig]

  routerList.forEach((item) => {
    router.addRoute('mainBox', {
      path: item.path,
      name: item.name,
      component: () => import(`@/views${item.component}`)
    })
  })
  // console.log(router.getRoutes());
  // RoutesConfig.forEach((item) => {
  //   router.addRoute('mainBox', item)
  // })
  // console.log('???11',routerList, RoutesConfig);
  // 改变isGetterRouter = true
  store.commit('changeGetterRouter', true)
}

const checkPermission = (item) => {
  // if (item.requireAdmin) {
  //   return store.state.userInfo.role === 1
  // }
  return true
}

export default router
